
import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';

typedef Future<dynamic> EventHandler(Map<String, dynamic> event);

class AlipushFlutter {

  static const String flutter_log = "| ALIPUSH | Flutter | ";
  //单例
  factory AlipushFlutter() => _instance;
  //平台通道
  final MethodChannel _channel;
  //方法回调
  EventHandler? _onReceiveNotification;
  EventHandler? _onOpenNotification;

  AlipushFlutter.private(MethodChannel channel)
      : _channel = channel;

  static final AlipushFlutter _instance =
  new AlipushFlutter.private(const MethodChannel('alipush'));

  ///初始化方法
  void setup({
    String appKey = '',
    String appSecret = ''
  }) {
    print(flutter_log + "setup:");
    _channel.invokeMethod('setup', {
      'appKey': appKey,
      'appSecret': appSecret
    });
  }

  //是否开启日志输出,默认关闭
  void setLogEnable(bool enable) {
    _channel.invokeMethod('setLogEnable', {'enable': enable});
  }

  ///事件传递
  ///onReceiveNotification 当应用处于前台状态收到推送
  /// onOpenNotification   当通过点击通知栏打开应用
  void addEventHandler({
    EventHandler? onReceiveNotification,
    EventHandler? onOpenNotification
  }) {
    print(flutter_log + "addEventHandler:");
    _onReceiveNotification = onReceiveNotification;
    _onOpenNotification = onOpenNotification;
    _channel.setMethodCallHandler(_handleMethod);
  }

  Future<dynamic> _handleMethod(MethodCall call) async {
    print(flutter_log + "_handleMethod:");
    switch (call.method) {
      case "onReceiveNotification":
        return _onReceiveNotification!(call.arguments.cast<String, dynamic>());
      case "onOpenNotification":
        return _onOpenNotification!(call.arguments.cast<String, dynamic>());
      default:
        throw new UnsupportedError("Unrecognized Event");
    }
  }

  ///设置别名，
  Future<int> setAlias(String alias) async {
    print(flutter_log + "setAlias:");
    int result = await _channel.invokeMethod('setAlias', alias);
    return result;
  }

  ///删除别名，alias = null or alias.length = 0 时，删除设备全部别名。
  Future<int> deleteAlias(String alias) async {
    print(flutter_log + "deleteAlias:");
    int result = await _channel.invokeMethod('deleteAlias');
    return result;
  }

  /// 设置应用 Badge（小红点）,iOS自动管理一般不需要设置
  Future setBadge(int badge) async {
    print(flutter_log + "setBadge:");
    await _channel.invokeMethod('setBadge', {"badge": badge});
  }

  ///当应用处于前台时收到推送，是否显示推送弹窗，默认否
  void setPushOnActive(bool active) async {
    print(flutter_log + "setPushOnActive:");
    await _channel.invokeMethod('setPushOnActive', {"active": active});
  }
}